import {Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {zip} from 'rxjs/observable/zip';
import {catchError} from 'rxjs/operators';
import {TranslateService} from '@ngx-translate/core';
import {App, MenuService, SettingsService, TitleService, User} from '@delon/theme';
import {ACLService} from '@delon/acl';
import {I18NService} from '../i18n/i18n.service';
import {AppUrl} from "../../app.url";
import {APP_ROLE} from "../../app.role";

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
    constructor(private menuService: MenuService,
                private translate: TranslateService,
                private i18n: I18NService,
                private settingService: SettingsService,
                private aclService: ACLService,
                private titleService: TitleService,
                private httpClient: HttpClient,
    ) {
    }

    load(): Promise<any> {
        // only works with promises
        // https://github.com/angular/angular/issues/15088
        return new Promise((resolve, reject) => {
            zip(
                this.httpClient.get(`assets/i18n/${this.i18n.defaultLang}.json`),
                this.httpClient.get('assets/app-data.json')
            ).pipe(
                // 接收其他拦截器后产生的异常消息
                catchError(([langData, appData]) => {
                    resolve(null);
                    return [langData, appData];
                })
            ).subscribe(([langData, appData]) => {

                    // setting language data
                    this.translate.setTranslation(this.i18n.defaultLang, langData);
                    this.translate.setDefaultLang(this.i18n.defaultLang);

                    // application data
                    const res: any = appData;
                    // 应用信息：包括站点名、描述、年份
                    this.settingService.setApp(res.app);
                    let user: User = {name: '游客'};
                    this.settingService.setUser(user);
                    this.aclService.setRole(['T']);
                    this.menuService.resume();
                    /**
                     * 设置用户权限
                     * 1、本地取出token
                     * 2、访问服务端验证，获得用户角色，若服务端未能从session中取出该用户信息
                     *    则设置为访客模式，清空本地token
                     * 3、若服务端验证通过，返回新token，查询用户角色等基本信息，设置用户权限
                     */

                    let _that = this;
                    this.httpClient.get(AppUrl.token.refresh).subscribe(token => {
                        let temp: any = token;
                        localStorage.setItem('token', 'Bearer ' + temp.token);
                        // 用户信息：包括姓名、头像、邮箱地址
                        this.httpClient.get(AppUrl.userInfo.getAll).subscribe(res => {
                            let temp: any = res;
                            let user: User = {name: temp.data.userInfo.username};
                            this.settingService.setUser(user);
                            /**
                             * 设置用户权限，更新菜单
                             */
                            this.aclService.setFull(false);
                            let roleType = temp.data.userInfo.roletype;
                            let abilities = temp.data.ability;
                            if (roleType.includes('A')  || roleType === 'B' || roleType === 'S') {
                                _that.aclService.setRole([roleType]);
                                let ability = [];
                                if (abilities&&abilities.length>0)
                                    abilities.forEach(e=>{ability.push(e.ability_value)});
                                _that.aclService.attachAbility(ability);
                            }
                            else {
                                _that.aclService.setRole(['T']);
                            }
                            _that.menuService.resume();
                            let appConf:App = {
                                name:'辛易校园',
                                description:'校园赞助平台',
                                menuShow:true
                            };
                            this.settingService.setApp(appConf);
                        });
                    }, () => {
                        this.errorHandler();
                    });
                    // ACL: 设置权限为游客模式  B 代表企业 A 代表管理员 T 代表游客 S 代表学生
                    // 初始化菜单
                    this.menuService.add(res.menu);
                    // 设置页面标题的后缀
                    this.titleService.suffix = res.app.name;

                },
                () => {
                    console.log('===================错误');
                },
                () => {
                    console.log('===================完成');

                    resolve(null);
                });
        });
    }

    private errorHandler() {
        let user: User = {name: '游客'};
        this.settingService.setUser(user);
        this.aclService.setRole(['T']);
        this.menuService.resume();
        if (localStorage.hasOwnProperty('token')&&localStorage.getItem('token')&&localStorage.getItem('token').length>10){
            alert('登录状态已失效,为保护您的账户安全,请重新登录');
        }
        localStorage.setItem('token','');

    }
}

